//
//  YSVoucherCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/8/6.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//  代金券

#import "YSVoucherCtrl.h"
#import "YSVoucherHeaderView.h"
#import "YSMineDataTool.h"
#import "YSVoucherCell.h"

@interface YSVoucherCtrl ()<UITableViewDataSource,UITableViewDelegate>
@property(strong, nonatomic) UILabel *nullPageLabel;
@property(weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,assign) float prodPrice;
@property(nonatomic,assign) int canUseCount;
@property(nonatomic,strong) NSMutableArray *voucherArray;
@property(nonatomic,strong) YSVoucherHeaderView *headerView;
@property(nonatomic,assign) BOOL isChoice;
@property(nonatomic,assign) SourceCtrlType type;
@end

@implementation YSVoucherCtrl

-(BOOL)shouldLogin{
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"代金券"];

    UILabel *nullPageLabel = [UIUtil getPageTipLabelWithTipText:@"暂无代金券哦"];
    [self.view addSubview:nullPageLabel];
    _nullPageLabel = nullPageLabel;
    
    _headerView = [YSVoucherHeaderView headerView];
    [_headerView setWidth:SCREENW];
    [_headerView setY:0];
    [self.view addSubview:_headerView];
    
    [self initWithTableView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(newVoucherCallBack:) name:kValidateVoucherSuccessNortif object:nil];
    
    if(_voucherArray.count){
        _canUseCount = [self getCanUseCount];
        if(_canUseCount == 0){
            [_nullPageLabel setHidden:NO];
        }else{
            [_nullPageLabel setHidden:YES];
        }
        [_tableView reloadData];
    }else{
        _voucherArray = [NSMutableArray array];
        [self requestData];
    }
    
}

+(instancetype)initWithPrice:(NSMutableArray *)voucherArray  prodPrice:(int)prodPrice isChoice:(BOOL)isChoice type:(SourceCtrlType) type{
    YSVoucherCtrl *result = [[YSVoucherCtrl alloc]init];
    result.prodPrice = prodPrice;
    result.voucherArray = voucherArray;
    result.isChoice = isChoice;
    result.type = type;
    return result;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

-(int)getCanUseCount{
    int canUseCount = 0;
    NSInteger count  = _voucherArray.count;
    for (int i = 0; i < count; i++) {
        if(_isChoice && ![_voucherArray[i] isPast]&& [_voucherArray[i] useAmount] <= _prodPrice){
            canUseCount++;
        }
    }
    return canUseCount;
}

-(void)newVoucherCallBack:(NSNotification *)nortif{
    NSString *voucherCode = [nortif object];
    if(ISBLANK(voucherCode)){
        ShowTips(@"验证码不能为空")
        return;
    }
    //调用验证代金券的接口
    [YSMineDataTool validateVoucherWithVoucherCode:voucherCode success:^(YSValidateVoucherRes *result) {
        if(result.isSucc){
            [self checkvoucherResult:result];
        }else{
            ShowEnterTips(result.data)
        }
    } failure:^(NSError *error) {
        ShowTips(kRequestFailure)
    }];
}

-(void)checkvoucherResult:(YSValidateVoucherRes*)result{
    UIAlertView *alert;
    NSString *status = nil;
    NSString *tipContent = nil;
    switch (result.result) {
        case 1://校验成功
            status = @"验证成功";
            tipContent = [NSString stringWithFormat:@"%ld元代金券已经添加到您的账户",result.voucher.amount];
            [_voucherArray insertObject:result.voucher atIndex:0];
            [_tableView reloadData];
            break;
        case 2://代金券不存在
            status = @"验证失败";
            tipContent = @"代金券不存在";
            break;
        case 3://代金券已被使用
            status = @"验证失败";
            tipContent = @"代金券已被使用";
            break;
        case 4://代金券已被绑定
            status = @"验证失败";
            tipContent = @"代金券已被绑定";
            break;
        case 5://代金券过期
            status = @"验证失败";
            tipContent = @"代金券已过期";
            break;
            
        default:
            break;
    }
    alert = [[UIAlertView alloc]initWithTitle:status message:tipContent delegate:self cancelButtonTitle:nil otherButtonTitles:@"知道了",nil];
    [alert show];
}

-(void)requestData{
    if(ISLOGIN){
        [YSMineDataTool getVoucherInfo:^(YSVoucherRes *result) {
            [UIUtil refreshComplete:self.tableView];
            if(result.isSucc){
                [_voucherArray removeAllObjects];
                [_voucherArray addObjectsFromArray:result.voucherList];
                [self.tableView reloadData];
                
                if(!_voucherArray.count){
                    [_nullPageLabel setHidden:NO];
                }else{
                    [_nullPageLabel setHidden:YES];
                }
            }else{
                ShowEnterTips(result.data);
            }
        } failure:^(NSError *error) {
            [UIUtil refreshComplete:self.tableView];
            ShowTips(kRequestFailure)
        }];
    }
}

-(void)initWithTableView{
     self.tableView.delegate = self;
     self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"YSVoucherCell" bundle:nil] forCellReuseIdentifier:@"YSVoucherCell"];
    [self.tableView setBackgroundColor:PUBLIC_BG];
    [self.tableView setTableFooterView:[UIView new]];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setY:CGRectGetMaxY(_headerView.frame)];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(_type == ACCOUNT_TYPE)
        return [self getCanUseCount];
    else
        return _voucherArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   YSVoucherCell *cell = [YSVoucherCell cellWithTableView:tableView];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [cell setVoucher:self.voucherArray[indexPath.row]];
   return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return YSVoucherCellHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSInteger useAmount = [_voucherArray[indexPath.row] useAmount];
    BOOL isPast = [_voucherArray[indexPath.row] isPast];
    if(_isChoice && !isPast && useAmount <= _prodPrice && _type == ACCOUNT_TYPE){
        //通知携带数据返回
        YSVoucher *voucher =  _voucherArray[indexPath.row];
        [[NSNotificationCenter defaultCenter] postNotificationName:kChooseVoucherFinishNortif object:voucher];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
